import { getInfo } from '@/api/user';
import { constantRoutes } from '@/router';
import storage from '@/utils/storage';
console.log('constantRoutes', constantRoutes);
const userStore: any = {
    namespaced: true,
    state: () => {
        return {
            token: storage.get('token'),
            name: '',
            avatar: '',
            routes: constantRoutes[0].children,
        };
    },

    mutations: {
        SET_TOKEN: (state: any, token: string) => {
            state.token = token;
        },
        SET_NAME: (state: any, name: string) => {
            state.name = name;
        },
        SET_AVATAR: (state: any, avatar: string) => {
            if (avatar.indexOf('http') !== -1) {
                state.avatar = avatar;
            } else {
                state.avatar = process.env.VUE_APP_BASE_API + avatar;
            }
        },
    },

    actions: {
        // get user info
        getInfo({ commit, state }: any) {
            return new Promise((resolve, reject) => {
                getInfo()
                    .then((response: any) => {
                        if (!response || !response.data) {
                            commit('SET_TOKEN', '');
                            storage.remove('token');
                            resolve('');
                        }

                        const {
                            roles,
                            name,
                            avatar,
                            introduction,
                            permissions,
                        } = response.data;

                        // roles must be a non-empty array
                        if (!roles || roles.length <= 0) {
                            reject('getInfo: roles must be a non-null array!');
                        }
                        commit('SET_PERMISSIONS', permissions);
                        commit('SET_ROLES', roles);
                        commit('SET_NAME', name);
                        commit('SET_AVATAR', avatar);
                        commit('SET_INTRODUCTION', introduction);
                        resolve(response);
                    })
                    .catch((error: any) => {
                        reject(error);
                    });
            });
        },
    },
};

export default userStore;
